<template>
  <div class="page">
    <MNavbar title="商品管理" :back="true" />
    
    <!-- 自定义确认弹窗 -->
    <div v-if="showConfirmDialog" class="dialog-overlay" @click="closeConfirmDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>{{ confirmDialog.title }}</h3>
        </div>
        <div class="dialog-body">
          <p>{{ confirmDialog.message }}</p>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-outline" @click="closeConfirmDialog">取消</button>
          <button class="btn btn-primary" @click="confirmAction">确定</button>
        </div>
      </div>
    </div>

    <!-- 顶部工具栏 -->
    <div class="section">
      <div class="card toolbar-card">
        <div class="toolbar-row">
          <input 
            class="search" 
            placeholder="搜索商品名称"
            v-model="searchKeyword"
            @input="handleSearch"
          />
          <div class="seg">
            <div 
              class="seg-item" 
              :class="{ active: currentStatus === null }"
              @click="filterByStatus(null)"
            >全部</div>
            <div 
              class="seg-item" 
              :class="{ active: currentStatus === 1 }"
              @click="filterByStatus(1)"
            >在售</div>
            <div 
              class="seg-item" 
              :class="{ active: currentStatus === 0 }"
              @click="filterByStatus(0)"
            >已下架</div>
            <div 
              class="seg-item" 
              :class="{ active: currentStatus === 2 }"
              @click="filterByStatus(2)"
            >库存预警</div>
          </div>
          <button class="btn btn-primary" @click="create">新增商品</button>
        </div>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="section">
      <div class="card product-table-container">
        <div class="table-head">
          <div>商品</div>
          <div>分类</div>
          <div>价格</div>
          <div>库存</div>
          <div>销量</div>
          <div>状态</div>
          <div>操作</div>
        </div>
        
        <!-- 商品列表项 -->
        <div v-if="productList.length > 0" class="product-list">
          <div 
            v-for="product in productList" 
            :key="product.productId" 
            class="product-item"
          >
            <div class="product-info">
              <img 
                :src="getProductImage(product.pic)" 
                :alt="product.name"
                class="product-image"
                @error="handleImageError"
              />
              <div class="product-details">
                <div class="product-name" :title="product.name">{{ product.name }}</div>
                <div class="product-meta">
                  <span class="product-id">ID: {{ product.productId }}</span>
                </div>
              </div>
            </div>
            
            <div class="product-category">{{ product.levelName || '未分类' }}</div>
            
            <div class="product-price">
              <div class="current-price">¥{{ formatPrice(product.price) }}</div>
              <div v-if="product.originalPrice && product.originalPrice > product.price" class="original-price">
                ¥{{ formatPrice(product.originalPrice) }}
              </div>
            </div>
            
            <div class="product-stock" :class="getStockClass(product.stock)">
              {{ product.stock || 0 }}
            </div>
            
            <div class="product-sales">
              {{ product.salesCount || 0 }}
            </div>
            
            <div class="product-status">
              <span class="status-badge" :class="getStatusClass(product.status)">
                {{ getStatusText(product.status) }}
              </span>
            </div>
            
            <div class="product-actions">
              <button class="btn btn-sm btn-outline" @click="editProduct(product)">
                编辑
              </button>
              <button 
                class="btn btn-sm" 
                :class="product.status === 1 ? 'btn-warning' : 'btn-success'"
                @click="toggleProductStatus(product)"
              >
                {{ product.status === 1 ? '下架' : '上架' }}
              </button>
              <button class="btn btn-sm btn-danger" @click="deleteProduct(product)">
                删除
              </button>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-else class="empty-state">
          <div class="empty-icon">📦</div>
          <div class="empty-text">{{ emptyText }}</div>
          <button class="btn btn-primary" @click="create">新增商品</button>
        </div>
        
        <!-- 分页 -->
        <div v-if="pagination.total > 0" class="pagination">
          <button 
            class="btn btn-outline" 
            :disabled="pagination.current <= 1"
            @click="changePage(pagination.current - 1)"
          >
            上一页
          </button>
          <span class="page-info">
            第 {{ pagination.current }} 页，共 {{ pagination.pages }} 页，总计 {{ pagination.total }} 条
          </span>
          <button 
            class="btn btn-outline" 
            :disabled="pagination.current >= pagination.pages"
            @click="changePage(pagination.current + 1)"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner">加载中...</div>
    </div>
  </div>
</template>

<script setup>
import MNavbar from '@/components/MNavbar.vue'
import { useRouter } from 'vue-router'
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const productList = ref([])
const searchKeyword = ref('')
const currentStatus = ref(null)
const pagination = ref({
  current: 1,
  size: 10,
  total: 0,
  pages: 0
})

// 确认弹窗相关
const showConfirmDialog = ref(false)
const confirmDialog = ref({
  title: '',
  message: '',
  onConfirm: null
})

// 搜索防抖
let searchTimer = null
// 请求去重
let currentRequest = null

// 页面加载时获取商品列表
onMounted(() => {
  loadProductList()
})

// 加载商品列表
async function loadProductList() {
  try {
    // 如果有正在进行的请求，取消它
    if (currentRequest) {
      currentRequest.cancel('新请求取消了前一个请求')
    }
    
    loading.value = true
    const params = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.size
    }
    
    // 只有当搜索关键词不为空时才添加name参数
    if (searchKeyword.value && searchKeyword.value.trim()) {
      params.name = searchKeyword.value.trim()
    }
    
    // 只有当状态不为null时才添加status参数
    if (currentStatus.value !== null) {
      params.status = currentStatus.value
    }
    
    console.log('请求参数:', params)
    
    // 创建可取消的请求
    const source = axios.CancelToken.source()
    currentRequest = source
    
    const response = await axios.get('/api/merchant/product/detail', { 
      params,
      cancelToken: source.token
    })
    
    console.log('响应数据:', response.data)
    
    if (response.data && response.data.records) {
      productList.value = response.data.records
      pagination.value = {
        current: response.data.current,
        size: response.data.size,
        total: response.data.total,
        pages: response.data.pages
      }
    } else {
      productList.value = []
      pagination.value.total = 0
      pagination.value.pages = 0
    }
  } catch (error) {
    // 如果是取消请求，不处理错误
    if (axios.isCancel(error)) {
      console.log('请求被取消:', error.message)
      return
    }
    console.error('加载商品列表失败:', error)
    console.error('错误详情:', error.response?.data || error.message)
    productList.value = []
    pagination.value.total = 0
    pagination.value.pages = 0
    // 这里可以添加错误提示
  } finally {
    currentRequest = null
    loading.value = false
  }
}

// 搜索处理
function handleSearch() {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    pagination.value.current = 1
    loadProductList()
  }, 500)
}

// 状态筛选
function filterByStatus(status) {
  currentStatus.value = status
  pagination.value.current = 1
  loadProductList()
}

// 分页
function changePage(page) {
  pagination.value.current = page
  loadProductList()
}

// 新增商品
function create() {
  router.push({ name: 'product-edit', query: { mode: 'create' } })
}

// 编辑商品
function editProduct(product) {
  router.push({ 
    name: 'product-edit', 
    query: { 
      mode: 'edit', 
      id: product.productId 
    } 
  })
}

// 切换商品状态
// 显示确认弹窗
function showConfirm(title, message, onConfirm) {
  confirmDialog.value = {
    title,
    message,
    onConfirm
  }
  showConfirmDialog.value = true
}

// 关闭确认弹窗
function closeConfirmDialog() {
  showConfirmDialog.value = false
  confirmDialog.value = {
    title: '',
    message: '',
    onConfirm: null
  }
}

// 确认操作
function confirmAction() {
  if (confirmDialog.value.onConfirm) {
    confirmDialog.value.onConfirm()
  }
  closeConfirmDialog()
}

// 切换商品状态
async function toggleProductStatus(product) {
  const newStatus = product.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '上架' : '下架'
  
  showConfirm(
    '状态修改确认',
    `确定要${action}商品"${product.name}"吗？`,
    async () => {
      try {
        loading.value = true
        
        // 调用API更新商品状态
        await axios.post(`/api/merchant/product/changeStatus?productId=${product.productId}&status=${newStatus}`)
        
        // 临时更新本地状态
        product.status = newStatus
        
        // 重新加载列表以确保数据一致性
        await loadProductList()
      } catch (error) {
        console.error('更新商品状态失败:', error)
        // 这里可以添加错误提示
      } finally {
        loading.value = false
      }
    }
  )
}

// 删除商品
async function deleteProduct(product) {
  if (confirm(`确定要删除商品"${product.name}"吗？此操作不可恢复！`)) {
    try {
      loading.value = true
      
      // 这里应该调用实际的API来删除商品
      await axios.post(`/api/merchant/product/delete?productId=${product.productId}`)
      
      // 重新加载列表
      await loadProductList()
    } catch (error) {
      console.error('删除商品失败:', error)
      // 这里可以添加错误提示
    } finally {
      loading.value = false
    }
  }
}

// 工具函数
function getProductImage(pic) {
  if (!pic) return '/images/default-product.gif'
  if (pic.startsWith('http')) return pic
  // 添加时间戳避免缓存问题导致的重复请求
  const imageUrl = `http://8.145.55.161:19000${pic.startsWith('/') ? pic : '/' + pic}`
  return imageUrl
}

function handleImageError(event) {
  // 避免无限循环，只有当前src不是默认图片时才设置
  if (event.target.src !== '/images/default-product.png' && 
      !event.target.src.includes('default-product.png')) {
    event.target.src = '/images/default-product.png'
  }
}

function formatPrice(price) {
  if (!price) return '0.00'
  return Number(price).toFixed(2)
}

function getStockClass(stock) {
  if (stock <= 0) return 'stock-empty'
  if (stock < 10) return 'stock-low'
  return 'stock-normal'
}

function getStatusClass(status) {
  switch (status) {
    case 1: return 'status-active'
    case 0: return 'status-inactive'
    default: return 'status-unknown'
  }
}

function getStatusText(status) {
  switch (status) {
    case 1: return '在售'
    case 0: return '已下架'
    default: return '未知'
  }
}

// 使用computed来缓存空状态文本，避免频繁计算
const emptyText = computed(() => {
  if (searchKeyword.value) {
    return `未找到包含"${searchKeyword.value}"的商品`
  }
  if (currentStatus.value !== null) {
    const statusText = getStatusText(currentStatus.value)
    return `暂无${statusText}商品`
  }
  return '暂无商品，点击"新增商品"开始上架'
})
</script>

<style scoped>
/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.2s ease-out;
}

.dialog-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  min-width: 320px;
  max-width: 90vw;
  animation: slideIn 0.3s ease-out;
}

.dialog-header {
  padding: 20px 24px 16px;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.dialog-body {
  padding: 20px 24px;
}

.dialog-body p {
  margin: 0;
  font-size: 16px;
  line-height: 1.5;
  color: #666;
}

.dialog-footer {
  padding: 16px 24px 20px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 工具栏样式 */
.toolbar-card { 
  padding: 16px; 
}

.toolbar-row { 
  display: flex; 
  gap: 12px; 
  align-items: center; 
}

.search { 
  flex: 1; 
  background: #fff; 
  border: 1px solid var(--border-color); 
  border-radius: 8px; 
  padding: 10px; 
  font-size: 14px;
}

.search:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.seg { 
  display: flex; 
  background: #f1f5f9; 
  border-radius: 10px; 
  padding: 4px; 
}

.seg-item { 
  padding: 6px 12px; 
  border-radius: 8px; 
  font-size: 12px; 
  color: var(--muted-text); 
  cursor: pointer;
  transition: all 0.2s ease;
  user-select: none;
}

.seg-item:hover {
  background: rgba(255, 255, 255, 0.5);
}

.seg-item.active { 
  background: #fff; 
  color: var(--text-color); 
  box-shadow: var(--shadow-sm); 
}

/* 商品表格容器样式 */
.product-table-container {
  max-width: 1200px;
  margin: 0 auto;
}

/* 表格样式 */
.table-head { 
  display: grid; 
  grid-template-columns: 2fr 1.2fr 1.2fr 1fr 1fr 1fr 1.5fr; 
  gap: 12px; 
  padding: 16px; 
  border-bottom: 1px solid var(--border-color); 
  color: var(--muted-text); 
  font-size: 12px;
  font-weight: 600;
  background: #f8fafc;
}

.table-head > div:nth-child(1) { text-align: center; }
.table-head > div:nth-child(2) { text-align: center; }
.table-head > div:nth-child(3) { text-align: center; }
.table-head > div:nth-child(4) { text-align: center; }
.table-head > div:nth-child(5) { text-align: center; }
.table-head > div:nth-child(6) { text-align: center; }
.table-head > div:nth-child(7) { text-align: center; }

/* 商品列表样式 */
.product-list {
  max-height: 600px;
  overflow-y: scroll;
  /* 隐藏滚动条但保持滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* 隐藏 Webkit 浏览器的滚动条 */
.product-list::-webkit-scrollbar {
  display: none;
}

.product-item {
  display: grid;
  grid-template-columns: 2fr 1.2fr 1.2fr 1fr 1fr 1fr 1.5fr;
  gap: 12px;
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
  align-items: center;
  transition: background-color 0.2s ease;
}

.product-item:hover {
  background-color: #f8fafc;
}

.product-item:last-child {
  border-bottom: none;
}

/* 商品信息样式 */
.product-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.product-image {
  width: 45px;
  height: 45px;
  border-radius: 8px;
  object-fit: cover;
  border: 1px solid var(--border-color);
  background: #f1f5f9;
  flex-shrink: 0;
}

.product-details {
  flex: 1;
  min-width: 0;
}

.product-name {
  font-weight: 500;
  color: var(--text-color);
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
}

.product-meta {
  font-size: 12px;
  color: var(--muted-text);
}

.product-id {
  font-family: monospace;
}

/* 其他列样式 */
.product-category {
  font-size: 12px;
  color: var(--text-color);
  padding: 2px 6px;
  background: #e2e8f0;
  border-radius: 4px;
  text-align: center;
}

.product-price {
  text-align: center;
}

.current-price {
  font-weight: 600;
  color: var(--text-color);
  font-size: 14px;
}

.original-price {
  font-size: 12px;
  color: var(--muted-text);
  text-decoration: line-through;
  margin-top: 2px;
}

.product-stock {
  text-align: center;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.stock-normal {
  color: #059669;
}

.stock-low {
  color: #d97706;
}

.stock-empty {
  color: #dc2626;
}

.product-sales {
  text-align: center;
  color: var(--muted-text);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

/* 状态样式 */
.product-status {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  text-transform: uppercase;
}

.status-active {
  background: #dcfce7;
  color: #166534;
}

.status-inactive {
  background: #fee2e2;
  color: #991b1b;
}

.status-unknown {
  background: #f1f5f9;
  color: var(--muted-text);
}

/* 操作按钮样式 */
.product-actions {
  display: flex;
  gap: 6px;
  justify-content: flex-end;
}

.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 11px;
}

.btn-primary {
  background: var(--primary-color, #3b82f6);
  color: white;
}

.btn-primary:hover {
  background: #2563eb;
}

.btn-outline {
  background: transparent;
  border: 1px solid var(--border-color);
  color: var(--text-color);
}

.btn-outline:hover {
  background: #f8fafc;
}

.btn-success {
  background: #10b981;
  color: white;
}

.btn-success:hover {
  background: #059669;
}

.btn-warning {
  background: #f59e0b;
  color: white;
}

.btn-warning:hover {
  background: #d97706;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn-danger:hover {
  background: #dc2626;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 48px 24px;
  color: var(--muted-text);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  margin-bottom: 24px;
  color: var(--muted-text);
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-top: 1px solid var(--border-color);
  background: #f8fafc;
}

.page-info {
  font-size: 14px;
  color: var(--muted-text);
}

/* 加载状态样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-spinner {
  padding: 20px 40px;
  background: white;
  border-radius: 8px;
  box-shadow: var(--shadow-lg);
  font-size: 16px;
  color: var(--text-color);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .table-head,
  .product-item {
    grid-template-columns: 2fr 0.8fr 1fr 1fr 0.8fr 0.8fr 0.8fr 1.2fr;
  }
}

@media (max-width: 768px) {
  .seg {
    display: none;
  }
  
  .toolbar-row {
    flex-direction: column;
    gap: 8px;
  }
  
  .search {
    width: 100%;
  }
  
  .table-head,
  .product-item {
    grid-template-columns: 1.5fr 0.8fr 0.8fr 0.8fr 0.8fr 1fr;
    font-size: 12px;
  }
  
  .product-category,
  .product-sales {
    display: none;
  }
  
  .product-actions {
    flex-direction: column;
    gap: 4px;
  }
  
  .pagination {
    flex-direction: column;
    gap: 12px;
  }
}

@media (max-width: 480px) {
  .product-item {
    grid-template-columns: 1fr;
    gap: 8px;
    padding: 12px;
  }
  
  .table-head {
    display: none;
  }
  
  .product-info {
    grid-column: 1;
  }
  
  .product-actions {
    grid-column: 1;
    justify-content: flex-start;
    flex-direction: row;
    flex-wrap: wrap;
  }
}
</style>

